/*
 * @lc app=leetcode.cn id=23 lang=javascript
 *
 * [23] 合并K个升序链表
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode[]} lists
 * @return {ListNode}
 */
var mergeKLists = function (lists) {
  // 合并K个升序链表
  let mergeTwoList = (l1, l2) => {
    let head = new ListNode()
    let dummy = head
    while (l1 && l2) {
      if (l1.val < l2.val) {
        head.next = l1
        l1 = l1.next
      } else {
        head.next = l2
        l2 = l2.next
      }
      head = head.next
    }
    if (l1) head.next = l1
    if (l2) head.next = l2

    return dummy.next
  }
  let length = lists.length
  if (length == 0) return null

  let list1 = lists[0]

  for (let i = 1; i < length; i++) {
    if (lists[i]) {
      list1 = mergeTwoList(list1, lists[i])
    }
  }
  return list1
}
// @lc code=end

// 两两合并
// 遍历数组，合并两个成新的一个链表再继续合并下一个链表
